package tianrun.ziguan.api.calculate.config.service.common.edit.asset;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.util.Assert;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.dto.request.common.DeleteBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.add.edit.SaveBody;
import tianrun.ziguan.api.calculate.config.entity.TAssetGroup;
import tianrun.ziguan.api.calculate.config.listener.RefreshCacheListener;
import tianrun.ziguan.api.calculate.config.service.asset.group.ITAssetGroupService;
import tianrun.ziguan.api.calculate.config.service.common.CommonService;
import tianrun.ziguan.api.calculate.config.service.common.edit.AbstractDealService;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.utils.MapUtil;
import tianrun.ziguan.api.common.util.SpringContextUtil;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class AssetGroupDealService extends AbstractDealService {

    public AssetGroupDealService(TGeTableConfigService tableConfigService) {
        super(tableConfigService);
    }

    @Override
    public void before(SaveBody body) {
        String name = MapUtil.getString(body.getData(), "name");

        LambdaQueryWrapper<TAssetGroup> wrapper = Wrappers.<TAssetGroup>lambdaQuery()
                .eq(TAssetGroup::getName, name);
        if (Objects.equals(body.getOption(), SaveBody.Option.EDIT)) {
            wrapper.ne(TAssetGroup::getId, body.getId());
        }
        ITAssetGroupService assetGroupService = SpringContextUtil.getBean(ITAssetGroupService.class);
        int count = assetGroupService.count(wrapper);
        Assert.isTrue(count == 0, "资产组名称："+name + "已存在！");
    }


    @Override
    public String tableName() {
        return "t_asset_group";
    }

    @Override
    public void after(SaveBody body) {
        String name = MapUtil.getString(body.getData(), "name");
        if (name!=null){
            RefreshCacheListener.flushByDeptNum(name);
        }
    }

    @Override
    public void delBefore(DeleteBody body) {

    }

    @Override
    public void listAfter(List<Map<String, Object>> result) {

    }

    @Override
    @Async("asyncServiceExecutor")
    public void delAfter(DeleteBody body) {
        CommonService commonService = SpringContextUtil.getBean(CommonService.class);
        List<Map<String, Object>> maps = commonService.listByIds(body.getTableName(), body.getIds(), true);
        maps.stream().map(map->MapUtil.getString(map,"name")).filter(Objects::nonNull).forEach(RefreshCacheListener::flushByDeptNum);
    }

    @Override
    public void infoAfter(Map<String, Object> bean) {

    }


}
